/**
 * 用户登录
 */
$(function() {
	//短信登录
	$('#shortMessageLogin').click(function () {
		$('.pwd-login').hide();
		$('.short-message-login').show();
	});
	//密码登录
	$('#pwdLogin').click(function () {
		$('.pwd-login').show();
		$('.short-message-login').hide();
	});
	//密码登录
	$('#btnUserLogin').click(function() {
		let userName = V('userName'), userPassword = V('userPassword');
		if (isNull(userName) || isNull(userPassword)) {
			setErrorMsg('请输入用户和密码');
			return;
		}
		let isPassVerify = V('isPassVerify');
		if (isPassVerify != 'S') {
			setErrorMsg('请拖动滑块完成验证');
			return;
		}
		setButtonStatus(this,true,'正在登录...');
        iAmLoginByPwd(this,userName,userPassword);
	});
	setVerImgDragPosition();
	initVerificationCode();
	$('#verifyImgSource').click(function() {
		initVerificationCode();
	});
	$('#verifyImgCut').click(function() {
		initVerificationCode();
	});
    //注册验证码拖动事件
    $('#drag').drag(null, null, initVerificationCode);
    //短信登录，获取验证码
    $('#btnGetCode').click(function() {
        let loginPhone = V('loginPhone');
        if(!phoneNumberIsRight(loginPhone)) {
            $('#smlPhoneError').text('请输入正确的手机号码');
            return;
        }
        //60秒倒计时
        countDownTime = 60;
        let btnGetCode = this;
        btnGetCode.disabled = true;
        $(this).css('cursor','unset').text(countDownTime + '秒后可点击');
        let checkCodeInterval = window.setInterval(function () {
            countDownTime --;
            if (countDownTime < 1) {
                window.clearInterval(checkCodeInterval);
                $(btnGetCode).css('cursor','pointer').text('获取验证码');
                btnGetCode.disabled = false;
            }else {
                $(btnGetCode).text(countDownTime + '秒后可点击');
            }
        },1000);
        //获取验证码
        getLoginCheckCode(loginPhone);
    });
    //验证码登录
    $('#btnLoginByCode').click(function() {
        let userName = V('userName'), checkCode = V('checkCode');
        if (isNull(userName) || isNull(checkCode)) {
            $('#smlPhoneError').text('请输入手机号和验证码');
            return;
        }
        setButtonStatus(this,true,'正在登录...');
        iAmLoginByCode(this,userName,checkCode);
    });
});
function setErrorMsg(errMsg) {
	I('errorPrompt').innerHTML = errMsg;
}

/**
 * 设置验证图片、小滑块的位置
 */
function setVerImgDragPosition() {
	$('.verification-code,#drag').css('margin-left',($('.pwd-login').width() - 260) / 2 + 'px');
}
/**
 * 密码登录
 * @param userName 登录的用户名
 * @param userPassword 登录的密码
 */
function iAmLoginByPwd(btnLogin,userName,userPassword) {
	let drag = $('#drag'), shaObj = new jsSHA("SHA-1", "TEXT");
	shaObj.update(userPassword);
	let hashPassword = shaObj.getHash("HEX");
	$.ajax({
		type : "POST",
		url : '/ventUserIndex/toLoginByPwd',
		data : {
			userName : userName,
			userPassword : hashPassword,
            rememberMe: true,
			dragMoveX: dragMoveX
		},
		dataType : 'json',
		cache : false,
		//async: false,
		success : function(result) {
			let msg = '', s = result.status;
			setErrorMsg('');
			if ("0" == s) {
				localStorage.setItem('me', JSON.stringify(result));
                historyBack();
			} else if (s == '1') {
				msg = '用户名或密码不能为空';
			} else if (s == '2' || s == '4') {
				msg = '验证失败，请拖动滑块完成验证';
			} else if (s == '3') {
				msg = '用户名或密码错误';
			} else if (s == '5') {
				msg = '您的账户已被冻结，如有疑问请联系客服';
            } else if (s == '6') {
                msg = '验证已失效，请刷新页面重新登录';
            }
			//如果登录失败
			if ("0" != s) {
                resetVerify(drag);
			}
            setButtonStatus(btnLogin,false,'登录');
			setErrorMsg(msg);
		},
		error: function() {
			setErrorMsg('登录失败');
            setButtonStatus(btnLogin,false,'登录');
            resetVerify(drag);
		}
	});
}

/**
 * 返回上一页
 */
function historyBack() {
    let backUrl = sessionStorage.getItem('backUrl');
    //如果不包含.html
    if(isNull(backUrl)){
        backUrl = '/';
    }else if (backUrl.indexOf('.html') < 1){
        backUrl += '.html';
    }
    sessionStorage.removeItem('backUrl');
    location.href = backUrl;
}
/**
 * 验证码登录
 * @param userName 登录的用户名
 * @param checkCode 验证码
 */
function iAmLoginByCode(btnLogin,userPhone,checkCode) {
    $.ajax({
        type : "POST",
        url : '/ventUserIndex/toLoginByCode',
        data : {
            userPhone : userPhone,
            code : checkCode
        },
        dataType : 'json',
        cache : false,
        success : function(codeLoginResult) {
            let msg = '登录失败', s = codeLoginResult.status;
            $('.sml-err').text('');
            if ("0" == s) {
                localStorage.setItem('ventUser', codeLoginResult);
                historyBack();
            } else if (s == '1') {
                msg = '手机号或验证码不能为空';
            } else if (s == '2') {
                msg = '验证码已失效，则重新获取';
            } else if (s == '3') {
                msg = '验证码错误';
            } else if (s == '6') {
                msg = '您的账户已被冻结，如有疑问请联系客服';
            } else if (s == '5') {
                msg = '用户不存在，请更换手机号再登录';
            }
            setButtonStatus(btnLogin,false,'登录');
            $('#smlCheckError').text(msg);
        },
        error: function() {
            $('#smlCheckError').text('登录失败');
            setButtonStatus(btnLogin,false,'登录');
        }
    });
}
/**
 * 重新设置滑动验证功能
 * @param drag 滑块对象
 */
function resetVerify(drag) {
    $('.loading,#verifyImgSource').hide();
    initVerificationCode();
    drag.css('background-color', '#e8e8e8');
    drag.empty();
    $('#verifyImgDrag').css('left',-10);
    drag.drag();
    $('.drag_text').css('color','black');
    let dragChildrenArray = drag.children();
    for(let g = 0; g < dragChildrenArray.length; g ++){
        let dragChildren = dragChildrenArray[g];
        if(dragChildren.innerText == '验证通过'){
            $(dragChildren).hide();
            break;
        }
    }
    $('.handler_ok_bg').hide();
}
/**
 * 初始化验证码图片信息
 */
function initVerificationCode() {
    $("#verifyImgDrag,#verifyImgSource,.verify-img-cut").css("display", "none");
    $(".verify-img-loading").show();
    let vis = $(".verify-img-source");
    $.ajax({
        type: "POST",
        async: true,
        url: "/ventIndex/makeImgVerifyCode?imgname=" + vis.css("background-image"),
        dataType: 'json',
        success: function (result) {
            if (!result) {
                alert('获取图形验证码失败');
                return;
            }
			//设置大图，小图，及其位置
			let verifyImgUrl = '../apiImages/';
			vis.css("background-image", "url(" + verifyImgUrl + "ventSourceVerifyImg/" + result.sourceImgName + ")");
			$(".verify-img-cut").css({
				"background": "url(" + verifyImgUrl + "ventTempVerifyImg/" + result.bigImgName + ") no-repeat",
				"display": "none"
			});
			$("#verifyImgDrag").css({
				"background": "url(" + verifyImgUrl + "ventTempVerifyImg/" + result.smallImgName + ") no-repeat",
				"top": result.location_y + "px"
			});
			$(".verify-img-loading").css("display", "none");
			vis.show();
        },
        error: function() {
        	alert("当前系统繁忙，请稍候再试");
        }
    });
}
/**
 * 获取登录验证码
 */
function getLoginCheckCode(loginPhone) {
    let errorMsg = $('#smlPhoneError'), errMsg = '当前系统繁忙,请稍后再获取验证码';
    $('.sml-err').text('');
    $.ajax({
        type: "POST",
        url: '/ventUserIndex/sendCodeByNoLogin',
        data:{phone: loginPhone},
        dataType: 'json',
        async: false,
        success: function(result) {
            let s = result.status;
            if(s == '1'){
                errMsg = '验证码已发送';
            }else if(s == '3'){
                errMsg = '该号码未注册';
            }else if(s == '4'){
                errMsg = '您当前IP地址获取验证码次数过多，请稍候再试';
            }else if(s == '5'){
                errMsg = '您当前手机号码获取验证码次数过多，请稍候再试';
            }else if(s == '6'){
                errMsg = '您输入的手机号码格式不对，请重新输入';
            }
            if (s != '1'){
                countDownTime = 0;
            }
            errorMsg.text(errMsg);
        },
        error: function() {
            errorMsg.text(errMsg);
        }
    });
}